package org.example.rubbish.service;

import org.example.rubbish.dto.AlarmDTO;
import org.example.rubbish.websocket.TerminalWebSocketServer;
import org.example.rubbish.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
public class UnifiedWebSocketService {  // ✅ 移除 Bak 后缀

    @Autowired
    @Lazy
    private WebSocketServer webSocketServer; // Vue管理端WebSocket

    @Autowired
    @Lazy
    private TerminalWebSocketServer terminalWebSocketServer; // 终端WebSocket

    /**
     * 统一广播新报警给所有客户端
     */
    public void broadcastAlarm(AlarmDTO alarmDTO) {
        System.out.println(">>> UnifiedWebSocketService 开始广播报警到所有端点");
        System.out.println(">>> 报警ID: " + alarmDTO.getAlarmId());

        // 广播给Vue管理端（报警页面）
        System.out.println(">>> 1. 广播到 Vue 管理端...");
        webSocketServer.broadcastAlarm(alarmDTO);

        // 广播给终端
        System.out.println(">>> 2. 广播到终端设备...");
        terminalWebSocketServer.broadcastAlarm(alarmDTO);

        System.out.println(">>> UnifiedWebSocketService 广播完成");
    }

    /**
     * 统一广播确认消息给所有客户端
     */
    public void broadcastAcknowledgment(String alarmId, String acknowledgedBy) {
        // 广播给Vue管理端
        webSocketServer.broadcastAcknowledgment(alarmId, acknowledgedBy);

        // 广播给终端
        terminalWebSocketServer.broadcastAcknowledgment(alarmId, acknowledgedBy);
    }

    /**
     * 获取总连接数
     */
    public int getTotalConnectionCount() {
        return webSocketServer.getConnectionCount() + terminalWebSocketServer.getConnectionCount();
    }

    /**
     * 获取连接统计
     */
    public ConnectionStats getConnectionStats() {
        return new ConnectionStats(
                webSocketServer.getConnectionCount(),
                terminalWebSocketServer.getConnectionCount(),
                getTotalConnectionCount()
        );
    }

    public static class ConnectionStats {
        private int vueClients;
        private int terminalClients;
        private int totalClients;

        public ConnectionStats(int vueClients, int terminalClients, int totalClients) {
            this.vueClients = vueClients;
            this.terminalClients = terminalClients;
            this.totalClients = totalClients;
        }

        // getter and setter
        public int getVueClients() { return vueClients; }
        public void setVueClients(int vueClients) { this.vueClients = vueClients; }
        public int getTerminalClients() { return terminalClients; }
        public void setTerminalClients(int terminalClients) { this.terminalClients = terminalClients; }
        public int getTotalClients() { return totalClients; }
        public void setTotalClients(int totalClients) { this.totalClients = totalClients; }
    }
}